package middleware

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/gofrs/uuid"
	"github.com/sirupsen/logrus"
	"gqlgen-test2/logger"
	"gqlgen-test2/server/constant"
	"time"
)

// 日志中间件
func LoggerMiddleware() gin.HandlerFunc {

	return func(c *gin.Context) {
		// Start timer
		start := time.Now()
		path := c.Request.URL.Path
		raw := c.Request.URL.RawQuery
		u, _ := uuid.NewV1()
		traceId := u.String()
		l := logger.LOG.WithFields(logrus.Fields{
			"traceId": traceId,
		})
		l.Debug(path, " ", "start")
		c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), constant.CONTEXT_LOG, l))
		c.Set(constant.CONTEXT_LOG, l)
		// Process request
		c.Next()
		end := time.Now()
		clientIp := c.ClientIP()
		method := c.Request.Method
		statusCode := c.Writer.Status()
		errorMessage := c.Errors.String()
		bodySize := c.Writer.Size()
		if raw != "" {
			path = path + "?" + raw
		}
		l.WithFields(logrus.Fields{
			"timeUse":  end.Sub(start).String(),
			"clientIp": clientIp,
			"method":   method,
			"status":   statusCode,
			"bodySize": bodySize,
			"errorMsg": errorMessage,
		}).Debug(path, " ", "end")
	}
}
